package bdqn.dao;

import java.sql.*;

public class BaseDao {
    protected Connection conn;
    protected PreparedStatement pstm;
    protected ResultSet rs;


    public Connection getConn() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            if (conn == null) {
                try {
                    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/meetingroom", "root", "root");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public void close(ResultSet rs, PreparedStatement pstm, Connection conn) {
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstm!=null){
            try {
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if  (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
    public int QueryUpdate(String sql,Object...param){
        int num=0;
        conn=getConn();
        try {
            pstm=conn.prepareStatement(sql);
            if (pstm!=null){
                for (int i = 0; i <param.length ; i++) {
                    pstm.setObject(i+1,param[i]);
                }
            }
            num=pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(null,pstm,conn);
        }

        return num;
    }
}
